package com.mangowang.module.main.ui;

/**
 * 文件名 : TiXianActivity
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 21:25
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.base.BaseActivity;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.WebApis;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.Index;
import com.mangowang.lib.common.proto.MemberBank;
import com.mangowang.lib.common.proto.Recharge;
import com.mangowang.lib.common.util.GsonUtils;
import com.mangowang.lib.common.util.InputMethodUtils;
import com.mangowang.lib.common.util.MoneyTextWatcher;
import com.mangowang.lib.common.util.StatusBarUtil;
import com.mangowang.lib.common.util.StringUtil;
import com.mangowang.module.main.web.ui.WebViewActivity;
import com.mangowang.module.main.R;
import com.mangowang.module.main.R2;
import com.ruffian.library.widget.RRelativeLayout;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TiXianActivity extends BaseActivity implements MoneyTextWatcher.CountAccountAndChargeInterface {
    @BindView(R2.id.back_iv)
    ImageView backIv;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.tv_bank_card_name)
    TextView tvBankCardName;
    @BindView(R2.id.rl_bank_card)
    RRelativeLayout rlBankCard;
    @BindView(R2.id.et_money)
    EditText etMoney;
    @BindView(R2.id.tv_balance)
    TextView tvBalance;
    @BindView(R2.id.tv_quan_bu_ti_xian)
    TextView tvQuanBuTiXian;
    @BindView(R2.id.ll_quan_bu_ti_xian)
    LinearLayout llQuanBuTiXian;
    @BindView(R2.id.tv_account_money)
    TextView tvAccountMoney;
    @BindView(R2.id.ll_shou_xun_fei)
    LinearLayout llShouXunFei;
    @BindView(R2.id.bt_ti_xian)
    Button btTiXian;
    private float balance = 0;
    private String card_id;
    private String mpassword;
    public static int GOTOBANKlIST = 100;
    public static int BACKTOWITHDRAW = 200;
    private MemberBank.bank bankCardBean;
    private String yu_er;
    private String pd_cash_service_charge = "0";
    private String single_pd_cash_price = "0";

    @BindView(R2.id.cb_check)
    CheckBox cbCheck;
    @BindView(R2.id.tv_xie_yi)
    TextView tv_xie_yi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ti_xian);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#FFFFFF"), true);
        tvTitle.setText(getIntent().getAction() + "提现");
        yu_er = getIntent().getStringExtra("yu_er");
        tvBalance.setText("余额 ¥ " + yu_er);
        balance = Float.valueOf(yu_er);
        if (getIntent().getStringExtra("isCash").equals("0")) {
            btTiXian.setEnabled(false);
            btTiXian.setText(getIntent().getStringExtra("errorMessage"));
        }
        loadView();
        initListener();
        loadSettingInfo();
    }

    private void loadSettingInfo() {
        Index.Get_pd_cash_setting_info.Builder builder = Index.Get_pd_cash_setting_info.newBuilder();
        builder.setWalletType(getIntent().getType());
        NetworkManager.INSTANCE.post(Apis.setting_info, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                pd_cash_service_charge = Index.Get_pd_cash_setting_info.parseFrom(response).getPdCashServiceCharge();
                single_pd_cash_price = Index.Get_pd_cash_setting_info.parseFrom(response).getSinglePdCashPrice();

            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void initListener() {
        tvQuanBuTiXian.setOnClickListener(view -> {
            etMoney.setText(yu_er);
        });

        rlBankCard.setOnClickListener(view -> {
        });
        btTiXian.setOnClickListener(view -> submit());
        backIv.setOnClickListener(view -> finish());
        //默认两位小数
        etMoney.addTextChangedListener(new MoneyTextWatcher(etMoney, this));

        tv_xie_yi.setOnClickListener(v -> {
            WebViewActivity.startActivity(mContext, WebApis.WithdrawalAgreement);
        });

    }

    /**
     * 加载银行卡数据
     */
    private void loadView() {
        NetworkManager.INSTANCE.post(Apis.member_bank, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                bankCardBean = MemberBank.get_bank.parseFrom(response).getArrayList().get(0);
                // 选中第一个银行卡
                String bank_card = bankCardBean.getBankCard();
                bank_card = bank_card.substring(bank_card.length() - 4);
                tvBankCardName.setText(bankCardBean.getBankName() + " (" + bank_card + ")");
                card_id = bankCardBean.getCardId() + "";
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    /**
     * 提交银行卡数据
     */
    private void submit() {
        InputMethodUtils.hideSoftInput(this);
        String money = etMoney.getText().toString();
        boolean empty = TextUtils.isEmpty(money);
        if (empty) {
            showToast("请先输入提现金额");
            return;
        }
        if (!cbCheck.isChecked()) {
            showToast("请先同意提现协议");
            return;
        }
        Recharge.Pd_cash_add.Builder builder = Recharge.Pd_cash_add.newBuilder();
        builder.setPdcAmount(money);
        builder.setWalletType(getIntent().getType());
        NetworkManager.INSTANCE.post(Apis.check_cash, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                if (errorCode == 200) {
                    Intent intent = new Intent(mContext, TiXianPayActivity.class);
                    intent.putExtra("message", tvBankCardName.getText().toString());
                    intent.putExtra("money", etMoney.getText().toString());
                    intent.putExtra("card_id", card_id);
                    intent.setType(getIntent().getType());
                    startActivity(intent);
                    finish();
                } else {
                    showToast(errorMessage);
                }

            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GOTOBANKlIST && resultCode == BACKTOWITHDRAW) {
            String infoString = data.getStringExtra("info");
            bankCardBean = GsonUtils.jsonToBean(infoString, MemberBank.bank.class);
            // 选中第一个银行卡
            String bank_card = bankCardBean.getBankCard();
            bank_card = bank_card.substring(bank_card.length() - 4);
            tvBankCardName.setText(bankCardBean.getBankName() + " (" + bank_card + ")");
            card_id = bankCardBean.getCardId() + "";
        }
    }

    @Override
    public void afterTextChang(String s) {
        if (TextUtils.isEmpty(s) || Double.parseDouble(s) == 0.0) {
            llQuanBuTiXian.setVisibility(View.VISIBLE);
            llShouXunFei.setVisibility(View.GONE);
            btTiXian.setEnabled(false);
        } else {
            btTiXian.setEnabled(!getIntent().getStringExtra("isCash").equals("0"));
            llQuanBuTiXian.setVisibility(View.GONE);
            llShouXunFei.setVisibility(View.VISIBLE);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            Double percentage = Double.valueOf(pd_cash_service_charge);
            Double monye = Double.valueOf(s);
            double c = monye * percentage;
            String cc1 = StringUtil.calculateProfit(c);
            Double aDouble = Double.valueOf(cc1);
            Log.e("songwang", "afterTextChang: " + c);
            StringBuilder text = new StringBuilder();
            if (c > 0) {
                text.append("扣除 ¥ " + cc1 + "服务费");
            }
            Double charge = Double.valueOf(single_pd_cash_price);
            if (charge > 0) {
                text.append(" 手续费 ¥ " + StringUtil.calculateProfit(charge));
            }
            double v = monye - aDouble - charge;
            if (v > 0) {
                text.append(" 实际到账金额 ¥ " + StringUtil.calculateProfit(v));
            }
            tvAccountMoney.setText(text.toString());
        }
    }


}
